package com.ssy.wireless.config;

import com.ssy.wireless.util.JacksonMapper;
import com.ssy.wireless.util.RespVo;
import lombok.extern.slf4j.Slf4j;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.web.servlet.HandlerExceptionResolver;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.PrintWriter;

/**
 * Created by cofey on 16/11/20.
 */
@Slf4j
public class WebExceptionResolver implements HandlerExceptionResolver {
    @Override
    public ModelAndView resolveException(HttpServletRequest request, HttpServletResponse response, Object o, Exception e) {
        response.setContentType(MediaType.APPLICATION_JSON_VALUE);
        response.setCharacterEncoding("UTF-8");
        response.setHeader("Cache-Control", "no-cache");
        try {
            PrintWriter pw = response.getWriter();
            response.setStatus(HttpStatus.OK.value());
            if (e instanceof IllegalArgumentException || e.getCause() instanceof IllegalArgumentException) {
                String msg = (e instanceof IllegalArgumentException ? e.getMessage() : e.getCause().getMessage());
                pw.write(JacksonMapper.getObjectMapper().writeValueAsString(RespVo.error(100, msg)));
            } else {
                log.error("系统异常", e);
                pw.write(JacksonMapper.getObjectMapper().writeValueAsString(RespVo.error(500, "请求失败,请重试")));
            }
            pw.flush();
        } catch (Exception ex) {
            ex.printStackTrace();
        }
        return new ModelAndView();
    }
}
